Imports System
Imports System.Configuration
Imports MyClasses
Imports DAL
Imports System.Text
Imports BAL

Public Class frmNgPurchase
    ' SUPPLIER IS REFERENCED AS PROMOTER (For minmal changes in code)
    '
#Region "Declaration"


    Private intTotalColumns As Integer = 21      'Purchase Item's no of Columns    

    Private btStatus As Byte                  'Current Record Status 
    Private intGrdCntRows As Integer = 1
    'Private intCrntItmCnt As Integer             'Used to show No of Active Items  in Current Counter
    Private BtLoading As Boolean                    'Variable is used to avoid unNecessary loops/events/execution while setting or Loading the Data                     

    Private intParty As Integer = 0           'Variable stores currently selected party 
    Private intPackSizeID As Integer = 0
    Private intPromoter As Integer = 0           'Variable stores currently selected promoter
    Private intColor As Integer = 0
    Private IntItem As Integer = 0
    Private intPriceList As Integer = 0
    Private intSite As Integer = 0
    Private intGodownID As Integer = 0
    Private intTaxID As Integer = 0
    Private intPackUpdateDtl_PK As Integer = 0
    Private intPackingID As Integer = 0
    Private PurchaseType As DGeneral.DocTypes
    Private intVoucherID As Int64
    Private intSearchedVoucherID As Int64
    Private iBillID As Integer = 0
    Dim dtbTaxes As DataTable
    Private hstTAxes As Hashtable
    Private dtbPacking As DataTable
    Private blnIsColor As Boolean = True
    Structure StructTaxDetails
        Dim intTax As Integer
        Dim StrTaxValue As Double
        Dim StrTotalTaxableAmt As Double
        Dim strTotalTaxApplied As Double
    End Structure
#End Region '"DECLARATION"

#Region " Form( & control) Events"
    
    Private Sub txtAmt_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTotalAmt.KeyDown, txtGrossAmt.KeyDown, txtOtherCharges.KeyDown
        e.SuppressKeyPress = True  'INSTEAD OF DISABLE CONTROL(IT AFFECTS THE UI) MANUAY KEYS ARE SUPPRESSED SO USER CANT EDIT  THE VALUE. TEXT BOX LOOKS ENABLE BUT NOT
    End Sub

    Private Sub txtReturn_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtGrossAmt.KeyDown
        e.SuppressKeyPress = True 'INSTEAD OF DISABLE CONTROL(IT AFFECTS THE UI) MANUAY KEYS ARE SUPPRESSED SO USER CANT EDIT  THE VALUE. TEXT BOX LOOKS ENABLE BUT NOT
    End Sub

    Private Sub txtPaidAmt_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtOtherCharges.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                btnSave.Focus()
            Else
                If e.Alt = True Then Exit Sub
                If BCommon.ValidateText(txtOtherCharges.Text, e.KeyCode, "NUM", False) = False Then
                    e.SuppressKeyPress = True
                ElseIf e.Shift Then
                    e.SuppressKeyPress = True : Exit Sub
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "txtPaidAmt_KeyDown")
        End Try
    End Sub

    Private Sub txtPaidAmt_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtOtherCharges.KeyUp
        Try
            If e.KeyCode = Keys.Enter Then
                If txtOtherCharges.Text >= txtTotalAmt.Text Then
                    txtGrossAmt.Text = Format((txtOtherCharges.Text - txtTotalAmt.Text), "##,##0.00")
                Else : txtGrossAmt.Text = "0.00"
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "txtPaidAmt_KeyUp")
        End Try
    End Sub

    Private Sub frmPurchase_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            'If DPurchase.GetCounterDetails().Rows.Count > 0 Then
            '    'Select Case MessageBox.Show(BCommon.GetMessage(10327), BCommon.GetConfigValues("MsgTitle"), MessageBoxButtons.YesNoCancel)
            '    Select Case BCommon.ShowMsgError(10327, "YNC")
            '        Case Windows.Forms.DialogResult.Yes      'SAVE All COUNTER DATA & CLOSE.
            '            'save data
            '            BCommon.ShowMsgError(3)
            '        Case Windows.Forms.DialogResult.No       'CLOSE THE FORM
            '            'NO NEED TO CODE
            '        Case Windows.Forms.DialogResult.Cancel   'CANCEL THE FORM CLOSE EVENT
            '            e.Cancel = True
            '    End Select
            'End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "frmPurchase_FormClosing")
        End Try
    End Sub

    Private Sub frmPurchase_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Size = Screen.PrimaryScreen.WorkingArea.Size
            BtLoading = True
            BCommon.SetFormStandards(Me)
            LoadTaxes()
            LoadPacking()
            Call DisplayData()
            txtPartyCode.Focus()
            Call BtnOrder_Click(Nothing, Nothing)
            BtLoading = False

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "frmPurchase_Load")
        End Try
    End Sub
#End Region

#Region "GRID SETTINGS"

    Private Sub SetGrids()
        Try
            'ITEM DISPLAY GRID
            With fgItems
                .Left = pnlMain.Left + 5
                .Width = pnlMain.Width - 1
                .RowHeadersVisible = False
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToOrderColumns = False
                .AllowUserToResizeRows = False
                .AllowUserToResizeColumns = False

                '.AllowDelete = True
                .RowCount = intGrdCntRows
                '.Cols.Fixed = 0
                .ColumnCount = intTotalColumns
                .ScrollBars = ScrollBars.Both
                '.AllowAddNew = False
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect




                'HIDDEN COLUMNS
                For intcnt As Integer = 0 To .ColumnCount - 1

                    .Columns(intcnt).Visible = False
                    .Columns(intcnt).ReadOnly = True
                    .Columns(intcnt).Width = 0

                    '  .Width = 0
                Next
                Call SetGridCaptions()
                .Columns(ItemGridColumns.CODE).Visible = True
                .Columns(ItemGridColumns.ITEMNAME).Visible = True
                .Columns(ItemGridColumns.CLRCODE).Visible = True
                .Columns(ItemGridColumns.CLRDESC).Visible = True
                .Columns(ItemGridColumns.PACK).Visible = True
                .Columns(ItemGridColumns.GODOWN).Visible = True
                .Columns(ItemGridColumns.QTY).Visible = True

                .Columns(ItemGridColumns.RecvQty).Visible = True
                .Columns(ItemGridColumns.DISC_AMT).Visible = False
                .Columns(ItemGridColumns.ReceivedQty).Visible = True
                .Columns(ItemGridColumns.AMOUNT).Visible = False
                .Columns(ItemGridColumns.TAXAMT).Visible = False
                .Columns(ItemGridColumns.TAXID).Visible = False
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetGrids")
        End Try
    End Sub

    Private Sub SetColumnWidths()
        Dim intColWidth As Integer = fgItems.Width / (11 * 3) '10 number of visible columns *3
        Try
            With fgItems

                .Columns(ItemGridColumns.CODE).Width = intColWidth * 3
                .Columns(ItemGridColumns.ITEMNAME).Width = intColWidth * 7
                .Columns(ItemGridColumns.CLRCODE).Width = intColWidth * 3
                .Columns(ItemGridColumns.CLRDESC).Width = intColWidth * 4
                .Columns(ItemGridColumns.PACK).Width = intColWidth * 4
                .Columns(ItemGridColumns.GODOWN).Width = intColWidth * 5
                .Columns(ItemGridColumns.QTY).Width = intColWidth * 2
                .Columns(ItemGridColumns.TAXID).Width = intColWidth * 1
                .Columns(ItemGridColumns.RecvQty).Width = intColWidth * 2
                '.Columns(ItemGridColumns.DISC_AMT).Width = intColWidth * 2
                .Columns(ItemGridColumns.ReceivedQty).Width = intColWidth * 2
                .Columns(ItemGridColumns.AMOUNT).Width = intColWidth * 2
                '.Columns(ItemGridColumns.TAXAMT).Width = intColWidth * 2


                txtItemCode.Width = .Columns(ItemGridColumns.CODE).Width
                txtItemName.Width = .Columns(ItemGridColumns.ITEMNAME).Width
                txtCLRCODE.Width = .Columns(ItemGridColumns.CLRCODE).Width
                txtCLRNAME.Width = .Columns(ItemGridColumns.CLRDESC).Width
                cmbPack.Width = .Columns(ItemGridColumns.PACK).Width
                txtGoDown.Width = .Columns(ItemGridColumns.GODOWN).Width
                txtQty.Width = .Columns(ItemGridColumns.QTY).Width
                txtDisc.Width = .Columns(ItemGridColumns.RecvQty).Width
                'txtDscAmt.Width = .Columns(ItemGridColumns.DISC_AMT).Width
                txtPrice.Width = .Columns(ItemGridColumns.ReceivedQty).Width
                txtItemAmount.Width = .Columns(ItemGridColumns.AMOUNT).Width


                txtItemCode.Left = .Left
                txtItemName.Left = txtItemCode.Left + txtItemCode.Width
                txtCLRCODE.Left = txtItemName.Left + txtItemName.Width
                txtCLRNAME.Left = txtCLRCODE.Left + txtCLRCODE.Width
                cmbPack.Left = txtCLRNAME.Left + txtCLRNAME.Width
                txtGoDown.Left = cmbPack.Left + cmbPack.Width

                txtQty.Left = txtGoDown.Left + txtGoDown.Width
                txtPrice.Left = txtQty.Left + txtQty.Width

                txtDisc.Left = txtPrice.Left + txtPrice.Width
                txtDscAmt.Left = txtDisc.Left + txtDisc.Width
                txtItemAmount.Left = txtPrice.Left + txtPrice.Width

            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetColumnWidths")
        End Try
    End Sub

    Private Sub SetGridCaptions()
        Try
            With fgItems
                'SET COLUMN NAMES
                .Columns(0).Name = "ITEMID"
                .Columns(1).Name = "CODE"
                .Columns(2).Name = "ITEMNAME"
                .Columns(3).Name = "CLRCODE"
                .Columns(4).Name = "CLRDESC"
                .Columns(5).Name = "PACK"
                .Columns(6).Name = "GODOWN"
                .Columns(7).Name = "QTY"
                .Columns(8).Name = "RATE"
                .Columns(9).Name = "DISCVALUE"
                .Columns(10).Name = "DISCAMT"
                .Columns(11).Name = "AMOUNT"
                .Columns(12).Name = "STATUS"

                .Columns(13).Name = "CLRID"
                .Columns(14).Name = "GODOWNID"

                .Columns(15).Name = "BILLID"
                .Columns(16).Name = "TAXID"

                .Columns(17).Name = "PACKID"
                .Columns(18).Name = "PACKUPDATEID"
                .Columns(19).Name = "TAXAMT"
                .Columns(20).Name = "PACKSIZEID"


                'SET COLUMN CAPTIONS
                .Columns(ItemGridColumns.ITEMID).HeaderText = "ITEMID"
                .Columns(ItemGridColumns.CODE).HeaderText = "CODE"
                .Columns(ItemGridColumns.ITEMNAME).HeaderText = "ITEMNAME"
                .Columns(ItemGridColumns.CLRCODE).HeaderText = "COLOR CODE"
                .Columns(ItemGridColumns.CLRDESC).HeaderText = "COLOR DESC"
                .Columns(ItemGridColumns.PACK).HeaderText = "PACK"
                .Columns(ItemGridColumns.GODOWN).HeaderText = "GODOWN"


                .Columns(ItemGridColumns.QTY).HeaderText = "QTY"
                .Columns(ItemGridColumns.ReceivedQty).HeaderText = "RECV QTY"
                .Columns(ItemGridColumns.RecvQty).HeaderText = "QTY"
                .Columns(ItemGridColumns.DISC_AMT).HeaderText = "DISC AMT"
                .Columns(ItemGridColumns.AMOUNT).HeaderText = "AMOUNT"
                .Columns(ItemGridColumns.STATUS).HeaderText = "STATUS"
                .Columns(ItemGridColumns.CLRID).HeaderText = "COLORID"
                .Columns(ItemGridColumns.GODOWNID).HeaderText = "GODOWNID"
                .Columns(ItemGridColumns.TAXID).HeaderText = "TAX ID"
                .Columns(ItemGridColumns.TAXAMT).HeaderText = "TAX APPLIED"
                .Columns(ItemGridColumns.PACK_SIZE_ID).HeaderText = "PACK ID"
                .Columns(ItemGridColumns.intPackUpdateDtl_PK).HeaderText = "PACKUPDATEID"
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetGridCaption")
        End Try
    End Sub

#End Region '"GRID SETTINGS"

#Region "GRID EVENT FUNCTIONS"
#End Region '"GRID EVENT FUNCTIONS"

#Region "BUTTON EVENTS"

    Private Sub BtnInvoice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnInvoice.Click
        Try
            ClearData()
            Me.BtnInvoice.BackColor = Color.SteelBlue
            Me.BtnGRN.BackColor = Color.WhiteSmoke
            Me.BtnOrder.BackColor = Color.WhiteSmoke
            PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE
            lblShipingAddress.Text = "Shipping Adress:"
            'subPriDisablePArtyOptions(True
            subPriEnableGRNOptions(False)
            txtSearchVoucher.Enabled = True
            btnSearchVoucher.Enabled = True
            txtGoDown.Enabled = False
            lblSearch.Text = "GRN N."
            txtSupplierDC.Text = String.Empty
            lblSupplierDC.Visible = True
            lblSupplierDC.Text = "SUPPLIER INVOICE"
            txtSupplierDC.Visible = True
            dgOtherCharges.Visible = True
            txtItemCode.Enabled = False
            txtItemName.Enabled = False
            txtCLRCODE.Enabled = False
            txtCLRNAME.Enabled = False
            cmbPack.Enabled = False
            txtQty.Enabled = False
            txtDisc.Enabled = False

            txtPrice.Enabled = True
            txtGoDown.Enabled = False

            txtDisc.Visible = False
            txtPrice.Visible = True
            txtSearchVoucher.Enabled = False
            pnlAmount.Visible = True
            SubPriSetSeqID()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "BtnInvoice_Click")
        End Try
    End Sub

    Private Sub BtnGRN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnGRN.Click
        Try
            ClearData()
            Me.BtnInvoice.BackColor = Color.WhiteSmoke
            Me.BtnGRN.BackColor = Color.SteelBlue
            Me.BtnOrder.BackColor = Color.WhiteSmoke
            PurchaseType = DGeneral.DocTypes.PURCHASE_GRN
            lblShipingAddress.Text = "Shipping Adress:"
            txtSearchVoucher.Enabled = True
            btnSearchVoucher.Enabled = True


            txtSupplierDC.Text = String.Empty
            lblSearch.Text = "PO N."
            lblSupplierDC.Visible = True
            txtSupplierDC.Visible = True
            lblSupplierDC.Text = "SUPPLIER DC"
            ' subPriDisablePArtyOptions(False)
            subPriEnableGRNOptions(True)
            'txtGoDown.Enabled = True
            dgOtherCharges.Visible = False
            SubPriSetSeqID()
            pnlAmount.Visible = False

            rTxtAddress.Enabled = False
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "BtnApprove_Click")
        End Try
    End Sub

    Private Sub subPriEnableGRNOptions(blnEnableDisble As Boolean)
        txtItemCode.Enabled = Not blnEnableDisble
        txtItemName.Enabled = Not blnEnableDisble
        txtCLRCODE.Enabled = Not blnEnableDisble
        txtCLRNAME.Enabled = Not blnEnableDisble
        cmbPack.Enabled = Not blnEnableDisble
        txtQty.Enabled = Not blnEnableDisble
        txtDisc.Enabled = blnEnableDisble

        txtPrice.Enabled = Not blnEnableDisble
        txtGoDown.Enabled = blnEnableDisble

        txtDisc.Visible = blnEnableDisble
        txtPrice.Visible = blnEnableDisble
        txtSearchVoucher.Enabled = Not blnEnableDisble '' SERACH SHOULD BE DONE FROM DIFFERENT FORM
        With fgItems

            .Columns(ItemGridColumns.TAXID).Visible = blnEnableDisble

            .Columns(ItemGridColumns.ReceivedQty).Visible = blnEnableDisble
            .Columns(ItemGridColumns.RecvQty).Visible = blnEnableDisble

            If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                .Columns(ItemGridColumns.ReceivedQty).Visible = True
                .Columns(ItemGridColumns.AMOUNT).Visible = True
                txtItemAmount.Visible = True
                .Columns(ItemGridColumns.ReceivedQty).HeaderText = "PRICE"
                .Columns(ItemGridColumns.QTY).HeaderText = "QTY"
                txtPrice.Visible = True
                txtItemAmount.Enabled = False
            Else
                txtItemAmount.Visible = False
                If blnEnableDisble Then
                    .Columns(ItemGridColumns.QTY).HeaderText = "ORDERED QTY"
                Else
                    .Columns(ItemGridColumns.QTY).HeaderText = "QTY"
                End If
                .Columns(ItemGridColumns.ReceivedQty).HeaderText = "RECV QTY"
                .Columns(ItemGridColumns.AMOUNT).Visible = False
            End If

        End With

    End Sub
    Private Sub BtnOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOrder.Click
        Try
            ' Me.BtnCash.BackColor = Color.WhiteSmoke
            'Me.BtnChallan.BackColor = Color.WhiteSmoke
            ClearData()
            Me.BtnInvoice.BackColor = Color.WhiteSmoke
            Me.BtnGRN.BackColor = Color.WhiteSmoke
            Me.BtnOrder.BackColor = Color.SteelBlue
            PurchaseType = DGeneral.DocTypes.PURCHASE_ORDER
            subPriEnableGRNOptions(False)
            txtSearchVoucher.Enabled = False
            btnSearchVoucher.Enabled = False
            txtGoDown.Enabled = False
            'lblShipingAddress.Text = "Shipping Adress:"
            'lblShipingAddress.Text = "Terms and Conditions:"
            SubPriSetSeqID()
            txtGoDown.Enabled = False
            rTxtAddress.Enabled = True
            lblSupplierDC.Visible = False
            txtSupplierDC.Visible = False
            txtSupplierDC.Text = String.Empty
            dgOtherCharges.Visible = False
            pnlAmount.Visible = False
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "Button5_Click")
        End Try
    End Sub

    Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
        ClearData()
    End Sub
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Try
            ' If btStatus = 1 Then 'Current Record is Updated 
            Me.Close()   'Current Record is not updated
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "btnClose_Click")
        End Try
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            '    If btStatus = 1 Then SaveCurrentItem(intCurrentRow)
            If ValidateInfo() = True Then
                If SaveData() = 1 Then

                    'BCommon.ShowMsgError(3)
                    Call ClearData()
                    BtnOrder_Click(Nothing, Nothing)
                Else
                    MessageBox.Show("ERROR")
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "btnSaveCounter_Click")
        End Try
    End Sub
    Private Sub SubPriSetSeqID()
        If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
            txtVoucher.Text = BCommon.GetSequentialID(DGeneral.DocTypes.PURCHASE_GRN)
        Else
            txtVoucher.Text = BCommon.GetSequentialID(PurchaseType)
        End If

    End Sub
#End Region  '"BUTTON EVENTS"


    Private Sub DisplayData()
        Try
            BtLoading = True
            'PurchaseType = DocTypes.CASH_MEMO
            '   FillPriceListCombo()
            SubPriSetTaxGrid()


            BCommon.SetTransationDate(dtpPurchaseDate)
            dtpPurchaseDate.Enabled = False


            SubPriSetSeqID()

            Call SetGrids()
            Call SetOtherCharges()
            Call SetColumnWidths()
            Call SetTabIndexes()

            BtLoading = False
            BtnOrder_Click(Nothing, Nothing)
            BCommon.SetTextReadOnly(txtVoucher)
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "DisplayData")
        End Try
    End Sub

    Private Sub ClearData()
        Try

            BtLoading = True

            btStatus = 0

            intVoucherID = 0
            intSearchedVoucherID = 0
            txtGrossAmt.Text = "0.00"
            txtTotalAmt.Text = "0.00"
            txtOtherCharges.Text = "0.00"

            subPriClearItemDtls()
            SetOtherCharges()
            'ClearTaxes()

            intPromoter = 0
            intParty = 0
            intSite = 0
            intPriceList = 0

            txtPartyCode.Text = String.Empty
            txtPartyName.Text = String.Empty
            txtPromoterCode.Text = String.Empty
            txtPromoterName.Text = String.Empty
            txtSiteCode.Text = String.Empty
            txtSiteName.Text = String.Empty
            rTxtAddress.Text = String.Empty
            txtSupplierDC.Text = String.Empty
            With fgItems
                .Rows.Clear()
                .Rows.Add(intGrdCntRows)
                .Refresh()
            End With
            BtLoading = False
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "ClearData")
        End Try
        fgItems.Enabled = True
        btnSave.Enabled = True
    End Sub

    Private Function SaveData() As Byte
        Try

            Dim objPurchaseItem() As CNGItem = SetPurchaseItemDetails()
            If objPurchaseItem.Length = 0 Then
                MessageBox.Show("Kindly select at least one product!")
                Return 0
            End If
            Dim objPurchase As CPurchase = SetPurchaseData()
            Dim objdPurchase As DPurchase = New DPurchase()
            Dim StrSeqId As String = objdPurchase.Save(objPurchase, objPurchaseItem, dgOtherCharges.DataSource, dgTaxes.DataSource, intVoucherID)

            If StrSeqId <> String.Empty AndAlso StrSeqId <> "0" Then
                If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                    If MessageBox.Show("Do you want to print the voucher :- " & StrSeqId.ToString, "NGS", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then

                        objdPurchase.updateBilledStatus()
                        '''''''''''''''''''''''''PRINTTING FRUNCTIONS NEDD TO BE CALL'''''''''''''''''''''''''''''''''''''''''''''''
                        '''''''''''''''''''''''''PRINTTING FRUNCTIONS NEDD TO BE CALL'''''''''''''''''''''''''''''''''''''''''''''''
                    End If
                End If
                Return 1
            Else
                Return 0
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SaveData")
            Return 0
        End Try
    End Function

    Private Function SetPurchaseData() As CPurchase
        Dim objPurchase As New CPurchase
        'Dim intCount As Integer
        Dim TotAmount As Double
        'Dim TotDisc As Double
        Try
            With objPurchase
                ' .PartyID = CustID
                .PurchaseDate = Me.dtpPurchaseDate.Value
                .IsFinalBill = True
                'For intCount = 1 To fgItems.Rows.Count
                '    If Not IsNothing(fgItems.Columns("ITEMID").Item(intCount)) Then
                '        TotAmount = TotAmount + fgItems.Columns("AMOUNT").Item(intCount)
                '    Else : Exit For
                '    End If
                'Next
                .PurchaseBillID = intVoucherID
                .PurchaseType = PurchaseType
                TotAmount = System.Convert.ToDouble(txtTotalAmt.Text.Trim())
                .Amount = TotAmount
                .dblOtherCharges = System.Convert.ToDouble(txtOtherCharges.Text.Trim())
                .Discount = 0
                .TotalTax = 0
                .PO_GRNID = intSearchedVoucherID
                .GrossAmt = System.Convert.ToDouble(txtGrossAmt.Text.Trim())
                .PartyID = intParty 'cmbPartyCode.SelectedValue
                .PromoterID = intPromoter 'CmbPromoterCode.SelectedValue
                .Site = intSite
                .priceListID = ConfigurationManager.AppSettings("DPL")
                .ShippingAdress = rTxtAddress.Text.Trim()
                .strSupplierDCNumber = txtSupplierDC.Text
                If intVoucherID > 0 AndAlso PurchaseType = DGeneral.DocTypes.PURCHASE_GRN AndAlso Me.BtnInvoice.BackColor = Color.SteelBlue Then
                    .blnConvertToInvoice = True
                End If
            End With
            Return objPurchase
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetPurchaseData")
            Return Nothing
        End Try
    End Function

    Private Function SetPurchaseItemDetails() As CNGItem()
        Dim objPurchaseItem() As CNGItem
        Dim intCount As Integer
        Dim intRowCount As Integer = 0
        Try
            For intCount = 0 To fgItems.Rows.Count - 1

                If fgItems.Item(ItemGridColumns.ITEMID, intCount).Value = Nothing OrElse Trim(fgItems.Item(ItemGridColumns.ITEMID, intCount).Value.ToString) = "" Then
                    Exit For
                Else
                    '  ReDim objPurchaseItem(intRowCount - 1)
                    ' objPurchaseItem(intRowCount - 1) =
                    intRowCount = intRowCount + 1
                End If
            Next
            ReDim objPurchaseItem(intRowCount - 1)
            For intCount = 0 To intRowCount - 1
                objPurchaseItem(intCount) = New CNGItem
                objPurchaseItem(intCount) = SetPurchaseItemDetail(intCount)
            Next
            Return objPurchaseItem
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetPurchaseItemDetails")
            Return Nothing
        End Try
    End Function

    Private Function SetPurchaseItemDetail(ByVal intRow As Integer) As CNGItem
        Dim Item As CNGItem = New CNGItem
        Try
            With Item
                .intPackSizeID = fgItems.Item(ItemGridColumns.PACK_SIZE_ID, intRow).Value
                .ColorCode = fgItems.Item(ItemGridColumns.CLRID, intRow).Value
                .ItemID = fgItems.Item(ItemGridColumns.ITEMID, intRow).Value
                .iBillID = IIf(IsNothing(fgItems.Item(ItemGridColumns.BILLID, intRow).Value), 0, fgItems.Item(ItemGridColumns.BILLID, intRow).Value)
                .Quantity = fgItems.Item(ItemGridColumns.QTY, intRow).Value
                If PurchaseType = DGeneral.DocTypes.PURCHASE_GRN Then
                    .intReceivedQuantity = IIf(IsNothing(fgItems.Item(ItemGridColumns.RecvQty, intRow).Value) OrElse fgItems.Item(ItemGridColumns.RecvQty, intRow).Value.ToString() = String.Empty, 0, fgItems.Item(ItemGridColumns.RecvQty, intRow).Value)
                Else
                    .intReceivedQuantity = 0
                End If


                .intPackUpdateDtl_PK = fgItems.Item(ItemGridColumns.intPackUpdateDtl_PK, intRow).Value

                .intGodownID = fgItems.Item(ItemGridColumns.GODOWNID, intRow).Value



                If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                    .dblRate = fgItems.Item(ItemGridColumns.ReceivedQty, intRow).Value
                    .Amount = fgItems.Item(ItemGridColumns.AMOUNT, intRow).Value
                Else
                    .dblRate = 0
                    .Amount = 0
                End If
                .dblDISCAmt = 0 ' fgItems.Item(ItemGridColumns.DISC_AMT, intRow).Value
                .strDisc = 0 'fgItems.Item(ItemGridColumns.DISC, intRow).Value
                .TaxID = fgItems.Item(ItemGridColumns.TAXID, intRow).Value
                .TaxAmt = 0 ' fgItems.Item(ItemGridColumns.TAXAMT, intRow).Value

            End With

            Return Item
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetPurchaseItemDetail")
            Return Nothing
        End Try
    End Function

    Private Function ValidateInfo() As Boolean
        '
        Try
            'If PurchaseType = DGeneral.DocTypes.CHALLAN OrElse PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
            '    If intParty = 0 Then
            '        MessageBox.Show("Please select Party!!", "NGS", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            '        txtPartyCode.Focus()
            '        Return False
            '    End If
            'End If
            If intPromoter = 0 Then
                MessageBox.Show("SELECT SUPPLIER", "NGS", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Return False

            End If
            Dim iTaxID As Integer = 0
            If PurchaseType = DGeneral.DocTypes.PURCHASE_GRN Then ''CHECK FOR SAME TAX ID
                For intCount As Integer = 0 To fgItems.Rows.Count - 1

                    If fgItems.Item(ItemGridColumns.ITEMID, intCount).Value = Nothing OrElse Trim(fgItems.Item(ItemGridColumns.ITEMID, intCount).Value.ToString) = "" Then
                        Exit For
                    Else
                        If iTaxID = 0 Then
                            iTaxID = fgItems.Item(ItemGridColumns.TAXID, intCount).Value
                        ElseIf iTaxID <> fgItems.Item(ItemGridColumns.TAXID, intCount).Value Then

                            MessageBox.Show("Selected Items are of different TAX", "NGS", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                            Return False
                        End If
                    End If
                Next
            End If
            Return True
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "ValidateInfo")
        End Try
    End Function

    'Private Sub FillPriceListCombo()
    '    Dim dtbPriceList As DataTable = DPurchase.GetPriceList()
    '    CmbPriceList.DataSource = dtbPriceList
    '    CmbPriceList.DisplayMember = "PRICELISTNAME"
    '    CmbPriceList.ValueMember = "ID"
    '    CmbPriceList.SelectedIndex = -1
    '    'intPriceList = CmbPriceList.SelectedValue
    'End Sub

#Region "ONLY FOR Purchase FORM"
    Private Sub SetTabIndexes()
        Try
            LblTotalOtherCharges.TabIndex = fgItems.TabIndex + 1
            txtOtherCharges.TabIndex = LblTotalOtherCharges.TabIndex + 1
            pnlAmount.TabIndex = txtOtherCharges.TabIndex + 1
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetTabIndexes")
        End Try
    End Sub

    Private Sub CalculateAmt()
        Dim intCount As Integer
        Dim TotAmount As Double = 0      '
        Dim TotalDiscAmt As Double = 0
        Try
            With fgItems

                'ClearTaxes()
                'ClearSummary()
                For intCount = 0 To .Rows.Count - 1
                    If PurchaseType = DGeneral.DocTypes.PURCHASE_GRN Then
                        If IsNothing(.Item(ItemGridColumns.ReceivedQty, intCount).Value) OrElse Trim(.Item(ItemGridColumns.ReceivedQty, intCount).Value) = "" Then Exit For
                    ElseIf PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                        If IsNothing(.Item(ItemGridColumns.AMOUNT, intCount).Value) OrElse Trim(.Item(ItemGridColumns.AMOUNT, intCount).Value) = "" Then Exit For
                        TotAmount = TotAmount + .Item(ItemGridColumns.AMOUNT, intCount).Value
                    End If



                    '   TotalDiscAmt = TotalDiscAmt + .Item(ItemGridColumns.DISC_AMT, intCount).Value
                    '  AddTaxes(.Item(ItemGridColumns.TAXID, intCount).Value, .Item(ItemGridColumns.TAXAMT, intCount).Value, .Item(ItemGridColumns.AMOUNT, intCount).Value)
                    'AddToSummary(.Item(ItemGridColumns.PACKINGID, intCount).Value, .Item(ItemGridColumns.QTY, intCount).Value)
                Next
                txtTotalAmt.Text = Format(TotAmount, "0.00")
                'txtTotalDisc.Text = Format(TotalDiscAmt, "0.00")
                CalculateTotalOtherCharges()
                SubPriUpdateAndDisplaySumary()
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "CalculateAmt")
        End Try
    End Sub
#End Region '"ONLY FOR Purchase FORM"


    Enum ItemGridColumns
        ITEMID = 0
        CODE = 1
        ITEMNAME = 2

        CLRCODE = 3
        CLRDESC = 4

        PACK = 5
        GODOWN = 6
        'SCHEMEID = 7
        'DISC = 8
        QTY = 7

        ReceivedQty = 8  'ALREADY RECEIVEDQUANTITY
        RecvQty = 9  '  QUANTITY to be Received in This GRN

        'DISC = 9
        DISC_AMT = 10

        AMOUNT = 11
        STATUS = 12

        CLRID = 13
        GODOWNID = 14

        BILLID = 15
        TAXID = 16
        PACK_SIZE_ID = 17
        intPackUpdateDtl_PK = 18
        TAXAMT = 19
        PACKINGID = 20
    End Enum
#Region "COMMON SEARCH"


    Private Sub txtPartyCode_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPartyCode.Enter, txtPartyName.Enter, txtItemCode.Enter, txtItemName.Enter, txtPromoterCode.Enter, txtPromoterName.Enter, txtCLRCODE.Enter, txtCLRNAME.Enter, txtSiteCode.Enter, txtSiteName.Enter, txtGoDown.Enter
        If BtLoading Then Exit Sub
        Select Case sender.Name
            ''Case txtPartyCode.Name, txtPartyName.Name

            ''   Return
            'Case txtPromoterCode.Name, txtPromoterName.Name
            '    strSearchString = "PROMOTER "
            '    Return "SELECT P.Id,P.PromoterCode AS CODE ,P.PromoterName AS NAME FROM [NGSPaintsDB].[dbo].promoter P WHERE P.IsDeleted=0"
            'Case txtSiteCode.Name, txtSiteName.Name
            '    strSearchString = "SITE "
            '    Return " SELECT [Id],[SiteCode]AS CODE ,[SiteName] AS NAME,ISNULL(PriceListId,0) AS PriceListId  FROM [NGSPaintsDB].[dbo].[Site] WHERE [IsDeleted]=0" & IIf(intParty > 0, " AND PartyID=" & intParty.ToString, "")
            'Case txtPrice.Name 'PRICE LIST

            'Case txtItemCode.Name, txtItemName.Name


            Case txtCLRCODE.Name, txtCLRNAME.Name
                If txtItemCode.Text.ToString.Trim = String.Empty Then
                    MessageBox.Show("Pleae Select Item Name")
                    txtItemCode.Focus()
                    Return
                End If

            Case txtGoDown.Name
                If cmbPack.Text.ToString.Trim = String.Empty Then
                    MessageBox.Show("Pleae Select Pack")
                    cmbPack.Focus()
                    Return
                End If
            Case txtQty.Name
                If txtGoDown.Text.ToString.Trim = String.Empty Then
                    MessageBox.Show("Pleae Select Godown")
                    txtGoDown.Focus()
                    Return
                End If
            Case txtDisc.Name
                If txtQty.Text.ToString.Trim = String.Empty Then
                    MessageBox.Show("Pleae enter Quantity")
                    txtQty.Focus()
                    Return
                End If
        End Select

        If sender.Text.ToString.Trim = String.Empty Then
            sender.BackColor = Color.LightBlue
            SearchParty_Promoter_Site(sender)
        End If
    End Sub
    Private Sub txtCLRCODE_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPartyCode.KeyDown, txtPartyName.KeyDown, txtItemCode.KeyDown, txtItemName.KeyDown, txtPromoterCode.KeyDown, txtPromoterName.KeyDown, txtCLRCODE.KeyDown, txtCLRNAME.KeyDown, txtSiteCode.KeyDown, txtSiteName.KeyDown, txtGoDown.KeyDown
        If (cmbPack.Name <> sender.Name) AndAlso e.KeyCode = Keys.Back Then
            e.SuppressKeyPress = True
            SearchParty_Promoter_Site(sender)
        ElseIf e.KeyCode = Keys.Enter Then
            SendKeys.Send("{Tab}")
        ElseIf e.KeyCode = Keys.Tab Then
        ElseIf (cmbPack.Name <> sender.Name) Then
            e.SuppressKeyPress = True
        End If
    End Sub

    Private Function GetSearchQuery(ByVal Sender As Object, ByRef strSearchString As String) As String
        Select Case Sender.Name
            Case txtPromoterCode.Name, txtPromoterCode.Name
                strSearchString = "SUPPLIER "
                Return "SELECT P.ID ,P.SupplierCode AS CODE,P.SupplierName AS NAME ,P.Address FROM Supplier P WHERE ISDELETED=0"
                'Case txtPromoterCode.Name, txtPromoterName.Name
                '    strSearchString = "PROMOTER "
                '    Return "SELECT P.Id,P.PromoterCode AS CODE ,P.PromoterName AS NAME FROM [NGSPaintsDB].[dbo].promoter P WHERE P.IsDeleted=0"
            Case txtSiteCode.Name, txtSiteName.Name
                strSearchString = "SITE "
                Return " SELECT [Id],[SiteCode]AS CODE ,[SiteName] AS NAME,ISNULL(PriceListId,0) AS PriceListId  FROM [NGSPaintsDB].[dbo].[Site] WHERE [IsDeleted]=0"
                'Case txtPrice.Name 'PRICE LIST
                'CmbPriceList.Focus()    Return "SELECT [ID],[PRICELISTCODE]AS CODE ,[PRICELISTNAME] AS NAME  FROM [NGSPAINTSDB].[DBO].[PRICELIST] WHERE [ISDELETED]=0"
            Case txtItemCode.Name, txtItemName.Name
                strSearchString = "PRODUCT "
                Return "SELECT P.[Id] AS ItemID,P.[ProductCode] AS Code,P.[ProductName] AS Name, P.TAXID,P.IsColor FROM [NGSPaintsDB].[dbo].Product P WHERE ISDeleted=0 ORDER BY NAME"
            Case txtCLRCODE.Name, txtCLRNAME.Name
                If IntItem = 0 Then
                    Return ""
                End If
                strSearchString = "COLOR "
                Return "SELECT DISTINCT C.[Id],C.[ColorCode] AS CODE ,C.[ColorDescription] AS NAME  FROM [Color] AS C  INNER JOIN  PackingUpdateDetail  D ON (D.ColorID=C.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE C.[IsDeleted]=0 AND C.ID > 0 AND P.ProductID=" & IntItem.ToString
            Case txtGoDown.Name
                'If IntItem = 0 OrElse intColor = 0 OrElse intPackSizeID = 0 Then
                If IntItem = 0 OrElse intPackSizeID = 0 OrElse (blnIsColor AndAlso intColor = 0) Then
                    Return ""
                End If
                strSearchString = "GODOWN "
                Return "SELECT DISTINCT (C.[Id]),C.[GoDownCode] AS CODE ,C.[GodownName] AS NAME , D.ID AS PackUpdateIDPK,D.PackingID,C.Priority FROM PackingUpdateDetail D INNER JOIN [GoDown] C ON (D.GoDownID=C.ID AND D.ColorID=" & intColor & ")  INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId AND P.ProductID=" & IntItem & ")  WHERE D.PackSizeID=" & intPackSizeID.ToString() & " Order by C.Priority"
            Case cmbPack.Name
                If IntItem = 0 OrElse (blnIsColor AndAlso intColor = 0) Then
                    Return ""
                End If
                strSearchString = "PACK "
                Return "SELECT DISTINCT S.ID, S.PackSize + ' ' + S.PackingDescription AS CODE FROM  PackingSize S INNER JOIN PackingUpdateDetail  D ON (D.PackSizeID=S.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE S.[IsDeleted]=0 AND P.ProductID=" & IntItem.ToString & " AND D.GodownId > 0  AND ColorID=" & intColor.ToString
            Case Else
                Return ""
        End Select
    End Function

    Private Sub SearchParty_Promoter_Site(ByVal sender As Object)
        Try
            Dim TxtSearch As TextBox = sender

            Dim frmListProducts As New frmProducts
            With frmListProducts

                .Left = fgItems.Right - .Width - 5
                .Top = fgItems.Top + 25
                .intSelectedItem = 0
                Dim strSearch As String = ""
                .StrSearchQuery = GetSearchQuery(TxtSearch, strSearch)
                If .StrSearchQuery = String.Empty Then Exit Sub
                .strSearchByCode = strSearch & IIf(sender.Name.ToString.ToUpper.Contains("CODE"), "CODE:", "NAME:")

                .txtProduct.Text = TxtSearch.Text

                .ShowDialog(Me)
                'intSelectedProduct = frmListProducts.intSelectedItem
            End With


            If frmListProducts.intSelectedItem > 0 Then
                With frmListProducts.fgProducts
                    If .CurrentRow.Index >= 0 Then
                        Select Case TxtSearch.Name
                            Case txtPartyCode.Name, txtPartyName.Name
                                intParty = .Item(0, .CurrentRow.Index).Value
                                txtPartyCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtPartyName.Text = .Item(2, .CurrentRow.Index).Value
                                ' Dim intLocPriceListID As Integer = .Item(4, .CurrentRow.Index).Value
                                'If intLocPriceListID > 0 Then
                                '    CmbPriceList.SelectedValue = intLocPriceListID
                                '    cmbPack_SelectionChangeCommitted(Nothing, Nothing)
                                'End If
                                rTxtAddress.Text = .Item(3, .CurrentRow.Index).Value
                                'If PurchaseType = DGeneral.DocTypes.QUOTATION Then
                                '    rTxtAddress.Text = funpriGetTermsAndConditions()
                                'Else
                                '    rTxtAddress.Text = .Item(3, .CurrentRow.Index).Value
                                'End If
                                lblChallanType.Text = .Item(5, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                If txtPartyCode.Name = TxtSearch.Name Then
                                    SendKeys.Send("{TAB}")
                                    SendKeys.Send("{TAB}")
                                Else
                                    SendKeys.Send("{TAB}")
                                End If
                            Case txtPromoterCode.Name, txtPromoterName.Name
                                intPromoter = .Item(0, .CurrentRow.Index).Value
                                txtPromoterCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtPromoterName.Text = .Item(2, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                If txtPromoterCode.Name = TxtSearch.Name Then
                                    SendKeys.Send("{TAB}")
                                    SendKeys.Send("{TAB}")
                                Else
                                    SendKeys.Send("{TAB}")
                                End If
                            Case txtSiteCode.Name, txtSiteName.Name
                                intSite = .Item(0, .CurrentRow.Index).Value
                                txtSiteCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtSiteName.Text = .Item(2, .CurrentRow.Index).Value
                                If PurchaseType = DGeneral.DocTypes.PURCHASE_ORDER Then
                                    rTxtAddress.Text = GetSiteAddress(intSite)
                                End If
                                'Dim intLocPriceListID As Integer = .Item(3, .CurrentRow.Index).Value
                                'If intLocPriceListID > 0 Then
                                '    CmbPriceList.SelectedValue = intLocPriceListID
                                '    cmbPack_SelectionChangeCommitted(Nothing, Nothing)
                                'End If
                                sender.BackColor = Color.White
                                If txtSiteCode.Name = TxtSearch.Name Then
                                    SendKeys.Send("{TAB}")
                                    SendKeys.Send("{TAB}")
                                Else
                                    SendKeys.Send("{TAB}")
                                End If
                            Case txtItemCode.Name, txtItemName.Name
                                subPriClearItemDtls()
                                IntItem = .Item(0, .CurrentRow.Index).Value
                                txtItemCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtItemName.Text = .Item(2, .CurrentRow.Index).Value
                                intTaxID = .Item(3, .CurrentRow.Index).Value
                                blnIsColor = .Item(4, .CurrentRow.Index).Value
                                If blnIsColor = False Then
                                    subPriUpdatePack()
                                End If
                                If txtItemCode.Name = TxtSearch.Name Then
                                    SendKeys.Send("{TAB}")
                                    SendKeys.Send("{TAB}")
                                Else
                                    SendKeys.Send("{TAB}")
                                End If
                            Case txtCLRCODE.Name, txtCLRNAME.Name
                                intColor = .Item(0, .CurrentRow.Index).Value
                                txtCLRCODE.Text = .Item(1, .CurrentRow.Index).Value
                                txtCLRNAME.Text = .Item(2, .CurrentRow.Index).Value
                                subPriUpdatePack()
                                sender.BackColor = Color.White
                                If txtCLRCODE.Name = TxtSearch.Name Then
                                    SendKeys.Send("{TAB}")
                                    SendKeys.Send("{TAB}")
                                Else
                                    SendKeys.Send("{TAB}")
                                End If
                                'cmbPack.DroppedDown = True
                            Case txtGoDown.Name ''
                                intGodownID = .Item(0, .CurrentRow.Index).Value
                                txtGoDown.Text = .Item(2, .CurrentRow.Index).Value
                                intPackUpdateDtl_PK = .Item(3, .CurrentRow.Index).Value
                                intPackingID = .Item(4, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                SendKeys.Send("{TAB}")
                            Case Else
                                Exit Sub
                        End Select
                    End If
                End With
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "showProductList")
        Finally
            sender.BackColor = Color.White
        End Try
    End Sub
#End Region
    Private Sub subPriUpdatePack()
        BtLoading = True
        Dim strPackQury As String = GetSearchQuery(cmbPack, "")
        Dim dtbpack As DataTable = DbHelper.ExecuteDataTable(strPackQury)
        Dim pk(0) As System.Data.DataColumn
        pk(0) = dtbpack.Columns(0)
        dtbpack.PrimaryKey = pk
        cmbPack.DataSource = dtbpack
        cmbPack.ValueMember = "ID"
        cmbPack.DisplayMember = "CODE"
        cmbPack.SelectedIndex = -1
        BtLoading = False

    End Sub

    Private Sub cmbPack_GotFocus(sender As Object, e As System.EventArgs) Handles cmbPack.GotFocus
        sender.DroppedDown = True
    End Sub
    Private Sub cmbPack_SelectionChangeCommitted(sender As Object, e As System.EventArgs) Handles cmbPack.SelectionChangeCommitted
        If BtLoading Then Exit Sub
        intPackSizeID = cmbPack.SelectedValue
        'SubPriGetPrice()
    End Sub
    'Private Sub txtPrice_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPrice.KeyDown
    '    If BCommon.ValidateText(txtPrice.Text.Trim, e.KeyCode, "NUM", True) = False Then
    '        e.SuppressKeyPress = True
    '    ElseIf e.KeyCode = Keys.Enter Then
    '        SendKeys.Send("{TAB}")
    '    End If
    'End Sub

    'Private Sub txtQty_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtQty.KeyDown
    '    If BCommon.ValidateText(txtQty.Text.Trim, e.KeyCode, "NUM", False) = False Then
    '        e.SuppressKeyPress = True
    '    ElseIf e.KeyCode = Keys.Enter Then
    '        SendKeys.Send("{TAB}")
    '    End If
    'End Sub

    'Private Sub txtPrice_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPrice.LostFocus ', txtQty.LostFocus
    '    'SubPriCalcItemAmnt()
    'End Sub

    Private Sub SubPriCalcItemAmnt()
        Try
            If Me.txtPrice.Text.ToString() <> String.Empty AndAlso Me.txtQty.Text.ToString() <> String.Empty Then
                txtItemAmount.Text = Convert.ToDouble(Me.txtPrice.Text.ToString()) * Convert.ToDouble(Me.txtQty.Text.ToString())
            Else
                txtItemAmount.Text = "0"
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
            txtItemAmount.Text = 0
        End Try
    End Sub
    Private Sub txtQty_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDisc.LostFocus, txtQty.LostFocus, txtPrice.LostFocus
        TextBox_LostFocus(sender, e)
        If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
            SubPriCalcItemAmnt()
        End If
        SetItemToGrid()
    End Sub
    Private Sub txtQty_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtQty.KeyDown, txtDisc.KeyDown, txtPrice.KeyDown
        If e.KeyCode = Keys.Enter Then
            If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                SubPriCalcItemAmnt()
            End If
            SetItemToGrid()
            SendKeys.Send("{Tab}")
        ElseIf BCommon.ValidateText(txtOtherCharges.Text, e.KeyCode, "NUM", True) = False Then
            e.SuppressKeyPress = True
        End If
    End Sub
    '
    Private Sub SetItemToGrid()
        Try
            If funPriIsValidItem() Then
                subPriSetItemInGrid()
                subPriClearItemDtls()
                txtItemCode.Focus()
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
    Private Sub txtAmount_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtItemAmount.LostFocus
        SetItemToGrid()
    End Sub
    Private Function funPriIsValidItem() As Boolean
        Try
            Dim BlnResult As Boolean = True
            If IntItem = 0 Then
                txtItemCode.Focus()
                BlnResult = False
            ElseIf (blnIsColor AndAlso intColor = 0) Then
                txtCLRCODE.Focus()
                BlnResult = False
                'ElseIf intGodownID = 0 Then
                '    txtGoDown.Focus()
                '    BlnResult = False
            ElseIf txtQty.Text = String.Empty OrElse System.Convert.ToInt64(txtQty.Text) <= 0 Then
                txtQty.Focus()
                BlnResult = False
                'ElseIf txtPrice.Text.Trim = String.Empty OrElse System.Convert.ToDouble(txtPrice.Text) <= 0 Then
                '    txtPrice.Focus()
                '    Return False
            ElseIf PurchaseType = DGeneral.DocTypes.PURCHASE_GRN Then
                If txtDisc.Text.Trim() = "" OrElse txtDisc.Text.Trim() = "0" Then
                    MessageBox.Show("Please enter Quantity.")
                    txtDisc.Focus()
                    Return False
                End If

                If System.Convert.ToInt16(txtDisc.Text) > (System.Convert.ToInt16(txtQty.Text) - System.Convert.ToInt16(txtPrice.Text)) Then
                    MessageBox.Show("Number of Received Quanitiy  is more than number of Quantity ordered.")
                    txtDisc.Text = (System.Convert.ToInt16(txtQty.Text) - System.Convert.ToInt16(txtPrice.Text))
                    txtDisc.Focus()
                    BlnResult = False
                ElseIf txtGoDown.Text.Trim() = String.Empty Then
                    txtGoDown.Focus()
                    MessageBox.Show("Please Select Godown.")
                    BlnResult = False
                End If
            ElseIf PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                If txtPrice.Text.Trim() = String.Empty Then
                    MessageBox.Show("Please enter Price.")
                    txtPrice.Focus()
                    BlnResult = False
                End If
            End If

            Return BlnResult
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
            Return False
        End Try
    End Function

    Private Sub subPriSetItemInGrid()
        Try


            With fgItems

                Dim intCurrentRow As Integer
                For intCurrentRow = 0 To .Rows.Count - 1
                    If IsNothing(.Item(ItemGridColumns.ITEMID, intCurrentRow).Value) OrElse .Item(ItemGridColumns.ITEMID, intCurrentRow).Value.ToString() = String.Empty Then
                        Exit For
                    End If
                Next
                If intCurrentRow = .Rows.Count Then
                    .Rows.Add(1)
                End If

                .Item(ItemGridColumns.CODE, intCurrentRow).Value = txtItemCode.Text

                .Item(ItemGridColumns.ITEMNAME, intCurrentRow).Value = txtItemName.Text
                .Item(ItemGridColumns.CLRCODE, intCurrentRow).Value = txtCLRCODE.Text
                .Item(ItemGridColumns.CLRDESC, intCurrentRow).Value = txtCLRNAME.Text
                .Item(ItemGridColumns.PACK, intCurrentRow).Value = cmbPack.Text
                .Item(ItemGridColumns.GODOWN, intCurrentRow).Value = txtGoDown.Text
                .Item(ItemGridColumns.ReceivedQty, intCurrentRow).Value = txtPrice.Text
                .Item(ItemGridColumns.QTY, intCurrentRow).Value = txtQty.Text
                .Item(ItemGridColumns.AMOUNT, intCurrentRow).Value = txtItemAmount.Text
                .Item(ItemGridColumns.RecvQty, intCurrentRow).Value = txtDisc.Text
                '.Item(ItemGridColumns.DISC_AMT, intCurrentRow).Value = txtDscAmt.Text

                .Item(ItemGridColumns.ITEMID, intCurrentRow).Value = IntItem

                .Item(ItemGridColumns.GODOWNID, intCurrentRow).Value = intGodownID
                .Item(ItemGridColumns.CLRID, intCurrentRow).Value = intColor
                .Item(ItemGridColumns.PACK_SIZE_ID, intCurrentRow).Value = intPackSizeID
                .Item(ItemGridColumns.intPackUpdateDtl_PK, intCurrentRow).Value = intPackUpdateDtl_PK
                .Item(ItemGridColumns.PACKINGID, intCurrentRow).Value = intPackingID ''used for summary
                .Item(ItemGridColumns.TAXID, intCurrentRow).Value = intTaxID
                .Item(ItemGridColumns.BILLID, intCurrentRow).Value = iBillID
                '               .Item(ItemGridColumns.TAXAMT, intCurrentRow).Value = CalculateItemTax(txtItemAmount.Text)
                '.Item(ItemGridColumns.GODOW, intCurrentRow).Value = intGodownID
                intCurrentRow = 0
                If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                    CalculateAmt()

                End If
                'CalculateTotalOtherCharges()

            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        Finally

        End Try
    End Sub
    Sub subPriClearItemDtls()
        Try
            txtItemCode.Text = String.Empty
            txtItemName.Text = String.Empty
            txtCLRCODE.Text = String.Empty
            txtCLRNAME.Text = String.Empty
            cmbPack.SelectedIndex = -1
            txtGoDown.Text = String.Empty
            txtQty.Text = String.Empty
            txtItemAmount.Text = String.Empty
            txtPrice.Text = String.Empty
            txtDisc.Text = String.Empty
            txtDscAmt.Text = String.Empty

            intPackSizeID = 0
            intColor = 0
            IntItem = 0
            iBillID = 0
            intGodownID = 0
            intPackUpdateDtl_PK = 0
            intPackingID = 0
            intTaxID = 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
    'Private Sub SubPriGetPrice()
    '    Try
    '        txtPrice.Text = DbHelper.ExecuteScalar("SELECT Rate FROM PriceListDetail WHERE PriceListID=" & intPriceList & " AND ProductID=" & IntItem & " AND PAckingID=" & intPackSizeID)
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
    '    End Try
    'End Sub

    Private Sub CmbPriceList_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        'If e.KeyCode = Keys.Enter Then
        '    SendKeys.Send("{Tab}")
        'End If
    End Sub

    'Private Sub CmbPriceList_SelectionChangeCommitted(sender As Object, e As System.EventArgs)
    '    If BtLoading Then Exit Sub
    '    If Not CmbPriceList.SelectedValue = Nothing Then
    '        intPriceList = CmbPriceList.SelectedValue
    '    End If
    'End Sub

    Private Sub fgItems_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles fgItems.DoubleClick
        With fgItems
            If Not IsNothing(.CurrentRow) AndAlso Not IsNothing(.Item(ItemGridColumns.ITEMID, .CurrentRow.Index).Value) Then
                Dim intCurrentRow As Integer = .CurrentRow.Index
                IntItem = .Item(ItemGridColumns.ITEMID, intCurrentRow).Value
                iBillID = IIf(IsNothing(.Item(ItemGridColumns.BILLID, intCurrentRow).Value), 0, .Item(ItemGridColumns.BILLID, intCurrentRow).Value)
                intPackSizeID = .Item(ItemGridColumns.PACK_SIZE_ID, intCurrentRow).Value
                txtQty.Text = .Item(ItemGridColumns.QTY, intCurrentRow).Value
                intColor = .Item(ItemGridColumns.CLRID, intCurrentRow).Value
                intPackUpdateDtl_PK = .Item(ItemGridColumns.intPackUpdateDtl_PK, intCurrentRow).Value
                intPackingID = .Item(ItemGridColumns.PACKINGID, intCurrentRow).Value
                intTaxID = .Item(ItemGridColumns.TAXID, intCurrentRow).Value
                intGodownID = .Item(ItemGridColumns.TAXID, intCurrentRow).Value
                txtItemCode.Text = .Item(ItemGridColumns.CODE, intCurrentRow).Value
                txtItemName.Text = .Item(ItemGridColumns.ITEMNAME, intCurrentRow).Value
                txtCLRCODE.Text = .Item(ItemGridColumns.CLRCODE, intCurrentRow).Value
                txtCLRNAME.Text = .Item(ItemGridColumns.CLRDESC, intCurrentRow).Value
                txtGoDown.Text = .Item(ItemGridColumns.GODOWN, intCurrentRow).Value
                txtPrice.Text = .Item(ItemGridColumns.ReceivedQty, intCurrentRow).Value
                txtDisc.Text = .Item(ItemGridColumns.RecvQty, intCurrentRow).Value
                txtDscAmt.Text = .Item(ItemGridColumns.DISC_AMT, intCurrentRow).Value
                txtItemAmount.Text = .Item(ItemGridColumns.AMOUNT, intCurrentRow).Value
                BCommon.IsColorProduct(IntItem, blnIsColor)
                subPriUpdatePack()
                cmbPack.SelectedValue = intPackSizeID
                .Rows.Remove(.CurrentRow)
            End If
        End With
    End Sub

    Private Sub fgItems_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles fgItems.KeyDown
        If e.KeyCode = Keys.Enter Then
            fgItems_DoubleClick(Nothing, Nothing)
        ElseIf e.KeyCode = Keys.Delete Then
            If MessageBox.Show("Do you want to delete record?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
                SubPriDeleteRecord()
            End If
        End If
    End Sub
    Private Sub SubPriDeleteRecord()
        Try
            With fgItems
                If Not IsNothing(.Item(ItemGridColumns.AMOUNT, .CurrentRow.Index).Value) Then
                    .Rows.Remove(.CurrentRow)
                End If
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        Finally
            'CalculateAmt()
            'CalculateTotalOtherCharges()
        End Try
    End Sub

    Private Sub SetOtherCharges(Optional ByVal boolLoadforBill As Boolean = False)

        Try
            'SET GRID
            With dgOtherCharges
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToOrderColumns = False
                .AllowUserToResizeRows = False
                .RowHeadersVisible = False
                Dim DtbOtherCharges As New DataTable

                If boolLoadforBill = True Then
                    DtbOtherCharges = DPurchase.GetPurchaseBillOtherCharges(intVoucherID)
                Else
                    DtbOtherCharges = DPurchase.GetOtherCharges()

                End If
                Dim pk(0) As System.Data.DataColumn
                pk(0) = DtbOtherCharges.Columns(0)
                DtbOtherCharges.PrimaryKey = pk
                .DataSource = DtbOtherCharges
                .Columns(0).Visible = False  'ID
                .Columns(4).Visible = False  'ISTAXABLE
                .Columns(1).ReadOnly = True 'NAME
                .Columns(3).ReadOnly = True 'Amount
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub CalculateTotalOtherCharges()
        Dim dblOtherCharges As Double = 0.0
        Dim strValue As String
        Try
            With dgOtherCharges
                For intRow As Int16 = 0 To .Rows.Count - 1
                    strValue = .Item(2, intRow).Value
                    .Item(3, intRow).Value = GetOtherCharge(strValue) * IIf(.Item(4, intRow).Value = True, DGeneral.OtherChargTAx, 1)
                    dblOtherCharges = dblOtherCharges + System.Convert.ToDouble(.Item(3, intRow).Value)
                Next
                txtOtherCharges.Text = dblOtherCharges
                txtGrossAmt.Text = System.Convert.ToDouble(txtTotalAmt.Text) + dblOtherCharges
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub dgOtherCharges_CellEndEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgOtherCharges.CellEndEdit
        CalculateTotalOtherCharges()
    End Sub
    Private Function GetOtherCharge(strValue As String) As Double
        If strValue.Contains("%") Then
            strValue = strValue.Replace("%", "")
            Dim DblValue As Double = Convert.ToDouble(strValue)
            Dim dblTotalAmt As Double = Convert.ToDouble(txtTotalAmt.Text)
            Return (DblValue * dblTotalAmt) / 100
        Else
            Return Convert.ToDouble(strValue)
        End If
    End Function
    Private Sub dgOtherCharges_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dgOtherCharges.KeyDown
        If BCommon.ValidateText(txtOtherCharges.Text, e.KeyCode, "NUM", True) = False Then
            If e.KeyCode <> Keys.A% Then
                e.SuppressKeyPress = True
            End If
        End If
    End Sub
#Region "SEARCH Purchase"
    Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
        SearchVoucher()

    End Sub
    Private Sub txtSearch_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
        If e.KeyCode = Keys.Enter Then
            SearchVoucher()
            Exit Sub
        End If
        If BCommon.ValidateText(txtSearch.Text.Trim, e.KeyCode, "NUM", False) = False Then
            e.SuppressKeyPress = True
        End If
    End Sub

    Private Sub SearchVoucher()
        Try
            If txtSearch.Text.Trim() = String.Empty OrElse System.Convert.ToInt16(txtSearch.Text) = 0 Then
                MessageBox.Show("Please Enter the ID", "NiranjanPaints", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else
                Dim intSeqVoucherID As Int64 = System.Convert.ToInt16(txtSearch.Text)

                intVoucherID = DbHelper.ExecuteScalar("SELECT PurchaseID FROM tPurchase WHERE SeqPurchaseID =" & intSeqVoucherID.ToString() & " AND PurchaseType=" & System.Convert.ToInt16(PurchaseType).ToString())
                If (intVoucherID > 0) Then
                    subPriFillDetails(String.Empty)
                    Select Case PurchaseType
                        Case DGeneral.DocTypes.PURCHASE_ORDER
                            fgItems.Enabled = True
                            btnSave.Enabled = True
                        Case DGeneral.DocTypes.PURCHASE_INVOICE
                            fgItems.Enabled = False
                            btnSave.Enabled = False
                        Case DGeneral.DocTypes.PURCHASE_GRN
                            fgItems.Enabled = True
                            btnSave.Enabled = True
                    End Select

                Else
                    MessageBox.Show("Record not found!!!", "NiranjanPaints", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
    Private Sub subPriFillDetails(ByVal StrPos As String)
        Dim intTempVoucherID As Integer = intVoucherID
        Try

            Call ClearData()
            Dim DtbPurchase As DataTable
            Dim dtbPurchaseItems As DataTable
            'Dim dtblocTaxes As DataTable
            If StrPos = String.Empty Then
                intVoucherID = intTempVoucherID
                DtbPurchase = DPurchase.GetPurchaseBill(intVoucherID)
                If PurchaseType = DGeneral.DocTypes.PURCHASE_ORDER Then
                    dtbPurchaseItems = DPurchase.GetPOBillItems(intVoucherID)
                ElseIf PurchaseType = DGeneral.DocTypes.PURCHASE_GRN Then

                    dtbPurchaseItems = DPurchase.GetPurBillItems4GRN_EDIT(intVoucherID)
                Else

                    dtbPurchaseItems = DPurchase.GetPurchaseBillItems(intVoucherID)
                    SetOtherCharges(True)
                End If

                'dtblocTaxes = DPurchase.GetPurchaseTaxes(intVoucherID)
                'LoadTaxes(dtblocTaxes)

            Else

                DtbPurchase = DPurchase.GetPurchaseBill(StrPos)
                If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                    intSearchedVoucherID = StrPos
                    dtbPurchaseItems = DPurchase.GetPurBillItems4_INVOICE(StrPos)
                Else
                    dtbPurchaseItems = DPurchase.GetPurBillItems4GRN(StrPos)
                End If
            End If
            If DtbPurchase.Rows.Count = 0 Then
                MessageBox.Show("Records not found")
                Return
            End If
            With DtbPurchase.Rows(0)
                'S.SeqPurchaseID,S.PartyCode AS PartyID,P.PartyCode,P.PartyName, S.PurchaseDate,S.PromoterID,R.PromoterName,R.PromoterCode,S.SiteID,S.Amount,S.OtherCharges,S.TotalTaxes,
                'S.Discount, S.GrossAmount, S.ShipingAddress, S.PurchaseType, PriceListID, T.SiteName, T.SiteCode
                ' PurchaseType = .Item("PurchaseType")
                If StrPos = String.Empty Then
                    txtVoucher.Text = .Item("SeqPurchaseID")
                Else

                End If
                'txtPartyCode.Text = .Item("PartyCode")
                'txtPartyName.Text = .Item("PartyName")
                txtPromoterCode.Text = .Item("PromoterCode")
                txtPromoterName.Text = .Item("PromoterName")

                'TxtTotalWithDisc.Text = System.Convert.ToDouble(txtTotalAmt.Text)
                If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE And intVoucherID > 0 Then
                    txtGrossAmt.Text = .Item("GrossAmount")
                    txtOtherCharges.Text = .Item("OtherCharges")
                    txtTotalAmt.Text = .Item("Amount")
                End If
                txtSiteCode.Text = .Item("SiteCode")
                txtSiteName.Text = .Item("SiteName")
                rTxtAddress.Text = .Item("ShipingAddress")


                'intParty = .Item("PartyID")
                intPromoter = .Item("PromoterID")
                intSite = .Item("SiteID")
                intPriceList = .Item("PriceListID")
                ' CmbPriceList.SelectedValue = intPriceList
                '.Text = .Item("")

                '''''-------------------------Item Details
            End With


            ''''''Fill Purchase Details
            'S.ItemID,P.ProductName,P.ProductCode,S.CLRcode AS CLRID,C.ColorCode,C.ColorDescription, S.PackUpdateID,S.PurchasePrice,S.Qty,S.Amount,S.SchemeDiscount SELECT S.ItemID,
            'P.ProductName,P.ProductCode,S.CLRcode AS CLRID,C.ColorCode,C.ColorDescription, S.PackUpdateID,S.PurchasePrice,S.Qty,S.Amount,S.SchemeDiscount, PCK 
            Dim intCurrentRow As Integer = 0
            For Each PurchaseITem As DataRow In dtbPurchaseItems.Rows

                If fgItems.Rows.Count <= intCurrentRow Then
                    fgItems.Rows.Add(intGrdCntRows)
                End If
                fgItems.Item(ItemGridColumns.CODE, intCurrentRow).Value = PurchaseITem.Item("ProductCode") 'txtItemCode.Text

                fgItems.Item(ItemGridColumns.ITEMNAME, intCurrentRow).Value = PurchaseITem.Item("ProductName") ' txtItemName.Text
                fgItems.Item(ItemGridColumns.CLRCODE, intCurrentRow).Value = PurchaseITem.Item("ColorCode") 'txtCLRCODE.Text
                fgItems.Item(ItemGridColumns.CLRDESC, intCurrentRow).Value = PurchaseITem.Item("ColorDescription") 'txtCLRNAME.Text
                fgItems.Item(ItemGridColumns.PACK, intCurrentRow).Value = PurchaseITem.Item("PCK") 'cmbPack.Text
                fgItems.Item(ItemGridColumns.GODOWN, intCurrentRow).Value = PurchaseITem.Item("GodownName") 'txtGoDown.Text
                fgItems.Item(ItemGridColumns.ReceivedQty, intCurrentRow).Value = PurchaseITem.Item("PurchasePrice") 'txtPrice.Text
                fgItems.Item(ItemGridColumns.QTY, intCurrentRow).Value = PurchaseITem.Item("Qty") 'txtQty.Text
                If (StrPos <> String.Empty) OrElse PurchaseType = DGeneral.DocTypes.PURCHASE_GRN Then
                    If PurchaseType = DGeneral.DocTypes.PURCHASE_GRN Then
                        fgItems.Item(ItemGridColumns.ReceivedQty, intCurrentRow).Value = PurchaseITem.Item("ReceivedQty") 'txtQty.Text
                    End If
                    fgItems.Item(ItemGridColumns.BILLID, intCurrentRow).Value = PurchaseITem.Item("PurchaseID")

                End If
                fgItems.Item(ItemGridColumns.AMOUNT, intCurrentRow).Value = PurchaseITem.Item("Amount") 'txtItemAmount.Text
                fgItems.Item(ItemGridColumns.RecvQty, intCurrentRow).Value = PurchaseITem.Item("DISC")
                fgItems.Item(ItemGridColumns.DISC_AMT, intCurrentRow).Value = PurchaseITem.Item("DISC_AMT")

                fgItems.Item(ItemGridColumns.ITEMID, intCurrentRow).Value = PurchaseITem.Item("ItemID") 'IntItem
                fgItems.Item(ItemGridColumns.GODOWNID, intCurrentRow).Value = PurchaseITem.Item("GodownId") 'intGodownID
                fgItems.Item(ItemGridColumns.CLRID, intCurrentRow).Value = PurchaseITem.Item("CLRID") 'intColor
                fgItems.Item(ItemGridColumns.PACK_SIZE_ID, intCurrentRow).Value = PurchaseITem.Item("PackSizeID") 'intPack
                fgItems.Item(ItemGridColumns.intPackUpdateDtl_PK, intCurrentRow).Value = PurchaseITem.Item("PackUpdateIDPK") 'intPackingUpdateID
                fgItems.Item(ItemGridColumns.PACKINGID, intCurrentRow).Value = PurchaseITem.Item("PackingID") ''FOR SUMARY DETAILS
                fgItems.Item(ItemGridColumns.TAXID, intCurrentRow).Value = PurchaseITem.Item("TAXID")
                fgItems.Item(ItemGridColumns.TAXAMT, intCurrentRow).Value = PurchaseITem.Item("TAXAMT")
                intCurrentRow += 1
            Next
            'intCurrentRow = 0
            ''''''Fill Other Charges
            If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then

                If intVoucherID > 0 Then
                    '  CalculateAmt() '@13.07.2014
                    SetOtherCharges(True)
                ElseIf StrPos.Length > 0 Then
                    CalculateAmt()

                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

#End Region

#Region "Summary"
    Private Sub LoadPacking()
        dtbPacking = DbHelper.ExecuteDataTable("SELECT Id,PackingContain AS COUNTS,PackingSizeId,PackingCode, PackingDescription AS Pack, 0 AS QTY FROM Packing WHERE IsDeleted=0")
        Dim pk(0) As System.Data.DataColumn
        pk(0) = dtbPacking.Columns(0)
        dtbPacking.PrimaryKey = pk
    End Sub
    Private Sub SubPriUpdateAndDisplaySumary()
        Dim strSmry As StringBuilder = New StringBuilder
        For Each drPack As DataRow In dtbPacking.Rows
            If (drPack.Item(5) > 0) Then
                If drPack.Item("QTY") < drPack.Item("COUNTS") Then
                    strSmry.Append(drPack.Item("PackingCode").ToString & "=" & drPack.Item("QTY").ToString() & "LOOSE")
                ElseIf drPack.Item("COUNTS") = drPack.Item("QTY") Then
                    strSmry.Append(drPack.Item("PackingCode").ToString & "=1" & drPack.Item("Pack").ToString())
                Else
                    Dim Qty As Int16 = drPack.Item("QTY") \ drPack.Item("COUNTS")
                    strSmry.Append(drPack.Item("PackingCode").ToString & "=" & Qty.ToString & drPack.Item("Pack").ToString() & ",")
                    strSmry.Append(drPack.Item("QTY") Mod drPack.Item("COUNTS") & "LOOSE")
                End If
                strSmry.Append(",")
            End If
        Next
        If strSmry.ToString.Length > 0 Then
            lblSummary.Text = strSmry.ToString
        End If
    End Sub

    Private Sub AddToSummary(ByVal locPackID As Int16, ByVal Qty As Integer)
        Try
            Dim PackRow As DataRow = dtbPacking.Rows.Find(locPackID)
            PackRow.Item(5) += Qty
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub ClearSummary()
        Try
            For Each drPack As DataRow In dtbPacking.Rows
                drPack.Item(5) = 0
            Next
            lblSummary.Text = "Summary:"
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

#End Region

#Region "Discount"
    Private Sub txtDscAmt_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtDscAmt.KeyDown
        e.SuppressKeyPress = True
        SendKeys.Send("{TAB}")
    End Sub
    Private Sub txtItemDsc_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtDisc.KeyDown
        If e.KeyCode = Keys.A% Then
        ElseIf BCommon.ValidateText(txtOtherCharges.Text, e.KeyCode, "NUM", True) = False Then
            e.SuppressKeyPress = True
        End If
    End Sub
    Private Sub txtDisc_Validated(sender As Object, e As System.EventArgs) Handles txtDisc.Validated

    End Sub
    'Private Sub txtItemDsc_TextChanged(sender As Object, e As System.EventArgs) Handles txtDisc.TextChanged
    'End Sub

    Private Function CalculateItemDisc(strValue As String, ByVal dblApplyTo As Double) As Double
        If strValue = String.Empty Then
            Return 0
        ElseIf strValue.Contains("%") Then
            strValue = strValue.Replace("%", "")
            Dim DblValue As Double = Convert.ToDouble(strValue)
            Return (DblValue * dblApplyTo) / 100
        Else
            Return Convert.ToDouble(strValue)
        End If
    End Function
#End Region

#Region "TAX"
    Private Function CalculateItemTax(dblAmt As Double) As Double
        If intTaxID = 0 Then Return 0
        Dim objStrctTax As StructTaxDetails = hstTAxes.Item(intTaxID)
        Dim dblTaxValue As Double
        If Not IsNothing(objStrctTax) Then
            dblTaxValue = objStrctTax.StrTaxValue
            Dim dblTaxAmt As Double
            dblTaxAmt = (dblTaxValue / (dblTaxValue + 100)) * dblAmt
            Return Format(dblTaxAmt, "0.00")
        End If
    End Function

    'Private Function funpriGetTermsAndConditions() As String
    '    Return "User Defined terms and conditions"
    'End Function
    Private Sub AddTaxes(ByVal LocTAXID As Int16, ByVal TAXAmt As Double, ByVal TotalAmt As Double)
        Try
            If LocTAXID > 0 Then
                Dim TaxRow As DataRow = dtbTaxes.Rows.Find(LocTAXID)
                TaxRow.Item(2) += TotalAmt - TAXAmt
                TaxRow.Item(3) += TAXAmt
                TaxRow.Item(4) += TotalAmt
                txtTaxableAmt.Text = txtTaxableAmt.Text + (TotalAmt - TAXAmt)
                txtTaxAmt.Text = txtTaxAmt.Text + TAXAmt
                txtTaxTotal.Text = txtTaxTotal.Text + TotalAmt
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub ClearTaxes()
        Try
            For Each drTax As DataRow In dtbTaxes.Rows
                drTax.Item(2) = 0
                drTax.Item(3) = 0
                drTax.Item(4) = 0
            Next
            txtTaxableAmt.Text = 0
            txtTaxAmt.Text = 0
            txtTaxTotal.Text = 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub LoadTaxes(Optional ByVal dtbPurchaseTax As DataTable = Nothing)
        Try
            hstTAxes = New Hashtable
            If IsNothing(dtbPurchaseTax) Then
                dtbTaxes = DbHelper.ExecuteDataTable("SELECT Id AS TAXID,TaxPercentage AS TAX,'0' AS TAXABLEAMT,'0' AS TAXAMT,'0' AS TOTAL FROM TAX WHERE IsDeleted=0")
            Else
                dtbTaxes = dtbPurchaseTax
                Dim dblTxbleAmt As Double
                Dim dblTaxAmt As Double
                For Each TaxRow As DataRow In dtbPurchaseTax.Rows
                    dblTxbleAmt += TaxRow.Item("TAXABLEAMT")
                    dblTaxAmt += TaxRow.Item("TAXAMT")
                Next
                txtTaxableAmt.Text = dblTxbleAmt
                txtTaxAmt.Text = dblTaxAmt
                txtTaxTotal.Text = dblTaxAmt + dblTxbleAmt
            End If
            Dim pk(0) As System.Data.DataColumn
            pk(0) = dtbTaxes.Columns(0)
            dtbTaxes.PrimaryKey = pk
            dgTaxes.DataSource = dtbTaxes
            Dim objStrctTax As StructTaxDetails = New StructTaxDetails
            For Each drTaxRow As DataRow In dtbTaxes.Rows
                With drTaxRow
                    objStrctTax.intTax = .Item(0)
                    objStrctTax.StrTaxValue = .Item(1)
                    objStrctTax.StrTotalTaxableAmt = 0
                    objStrctTax.strTotalTaxApplied = 0
                End With
                hstTAxes.Add(objStrctTax.intTax, objStrctTax)
            Next

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
    Private Sub SubPriSetTaxGrid()
        Try
            With dgTaxes
                '.ColumnCount = 5
                .Columns(0).HeaderText = "ID"
                .Columns(0).Visible = False
                .Columns(1).HeaderText = "Tax"
                .Columns(2).HeaderText = "Taxable Amt"
                .Columns(3).HeaderText = "Tax Amt"
                .Columns(4).HeaderText = "Total"
                .Columns(1).Width = .Width / 6
                .Columns(2).Width = .Width / 3.3
                .Columns(3).Width = .Width / 4
                .Columns(4).Width = .Width / 5
                .Columns(1).ReadOnly = True
                .Columns(2).ReadOnly = True
                .Columns(3).ReadOnly = True
                .Columns(4).ReadOnly = True
                txtTaxableAmt.Width = .Width / 3.3
                txtTaxAmt.Width = .Width / 4
                txtTaxTotal.Width = .Width / 5
                .RowHeadersVisible = False
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
#End Region


#Region "SEARCH TO CONVERT"
    Private Sub btnSearchVoucher_Click(sender As System.Object, e As System.EventArgs) Handles btnSearchVoucher.Click
        If PurchaseType = DGeneral.DocTypes.PURCHASE_ORDER Then
            SearchVoucherToconvert()
        Else
            Dim objSearchPo As frmSearchPO = New frmSearchPO
            objSearchPo.Left = Me.Right - objSearchPo.Width
            If PurchaseType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                objSearchPo.SearchType = DGeneral.DocTypes.PURCHASE_GRN
            Else
                objSearchPo.SearchType = DGeneral.DocTypes.PURCHASE_ORDER
            End If

            objSearchPo.ShowDialog(Me)

            If objSearchPo.strPOs = String.Empty Then

            Else
                subPriFillDetails(objSearchPo.strPOs)
                

            End If
        End If
    End Sub
    Private Sub txtSearchVoucher_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtSearchVoucher.KeyDown
        If e.KeyCode = Keys.Enter Then
            btnSearchVoucher_Click(btnSearchVoucher, Nothing)
            Exit Sub
        End If
        If BCommon.ValidateText(txtSearchVoucher.Text.Trim, e.KeyCode, "NUM", False) = False Then
            e.SuppressKeyPress = True
        End If
    End Sub
    Private Sub SearchVoucherToconvert()
        Try
            If txtSearchVoucher.Text.Trim() = String.Empty OrElse System.Convert.ToInt16(txtSearchVoucher.Text) = 0 Then
                MessageBox.Show("Please Enter the ID", "NiranjanPaints", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else
                Dim intSeqVoucherID As Int64 = System.Convert.ToInt16(txtSearchVoucher.Text)
                Dim LocPurchaseType As DGeneral.DocTypes
                Select Case (PurchaseType)
                    Case DGeneral.DocTypes.PURCHASE_GRN
                        LocPurchaseType = DGeneral.DocTypes.PURCHASE_ORDER
                    Case DGeneral.DocTypes.PURCHASE_INVOICE
                        LocPurchaseType = DGeneral.DocTypes.PURCHASE_GRN
                End Select
                intVoucherID = DbHelper.ExecuteScalar("SELECT PurchaseID FROM tPurchase WHERE SeqPurchaseID =" & intSeqVoucherID.ToString() & " AND PurchaseType=" & System.Convert.ToInt16(LocPurchaseType).ToString())
                If (intVoucherID > 0) Then
                    LocPurchaseType = PurchaseType
                    Try

                        subPriFillDetails(String.Empty)
                    Catch ex As Exception
                        BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
                    Finally
                        If PurchaseType <> DGeneral.DocTypes.PURCHASE_GRN Then
                            intSearchedVoucherID = intVoucherID
                            intVoucherID = 0
                        End If
                        PurchaseType = LocPurchaseType
                    End Try
                Else
                    MessageBox.Show("Record not found!!!", "NiranjanPaints", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
#End Region

    Private Function GetSiteAddress(ByVal iSiteCode As Int32) As String
        Return DbHelper.ExecuteScalar("SELECT ISNULL( S.Address +', PIN:' + CONVERT(VARCHAR (6),S.PinCode) +', ' + C.CityName  ,'')  AS Addrs FROM SITE S INNER JOIN City C ON (S.CityID= C.ID)WHERE S.IsDeleted=0 AND S.ID=" & iSiteCode.ToString())
    End Function

    Private Sub txtPrice_TextChanged(sender As Object, e As System.EventArgs) Handles txtPrice.TextChanged
        SubPriCalcItemAmnt()
    End Sub

    Private Sub TextBox_GotFocus(sender As Object, e As System.EventArgs) Handles txtGrossAmt.GotFocus, txtTotalAmt.GotFocus, txtOtherCharges.GotFocus, txtTotalDisc.GotFocus, txtPartyCode.GotFocus, txtPartyName.GotFocus, txtSiteCode.GotFocus, txtSiteName.GotFocus, txtPromoterCode.GotFocus, txtPromoterName.GotFocus, txtItemCode.GotFocus, txtItemName.GotFocus, txtCLRCODE.GotFocus, txtCLRNAME.GotFocus, txtGoDown.GotFocus, txtQty.GotFocus, txtPrice.GotFocus, txtDisc.GotFocus, txtDscAmt.GotFocus, txtItemAmount.GotFocus, txtSearch.GotFocus, txtSearchVoucher.GotFocus
        Dim txtobject As TextBox = sender
        txtobject.BackColor = Color.LightBlue
    End Sub

    Private Sub TextBox_LostFocus(sender As Object, e As System.EventArgs) Handles txtGrossAmt.LostFocus, txtTotalAmt.LostFocus, txtOtherCharges.LostFocus, txtTotalDisc.LostFocus, txtPartyCode.LostFocus, txtPartyName.LostFocus, txtSiteCode.LostFocus, txtSiteName.LostFocus, txtPromoterCode.LostFocus, txtPromoterName.LostFocus, txtItemCode.LostFocus, txtItemName.LostFocus, txtCLRCODE.LostFocus, txtCLRNAME.LostFocus, txtGoDown.LostFocus, txtDscAmt.LostFocus, txtItemAmount.LostFocus, txtSearch.LostFocus, txtSearchVoucher.LostFocus
        Dim txtobject As TextBox = sender
        txtobject.BackColor = Color.White
    End Sub
    Private Sub txtPartyCode_Leave(sender As Object, e As System.EventArgs) Handles txtPartyCode.Leave, txtPartyName.Leave
        If sender.Text.trim = String.Empty Then
            intParty = 0
        End If
    End Sub
    Private Sub txtSite_Leave(sender As Object, e As System.EventArgs) Handles txtSiteCode.Leave, txtSiteName.Leave
        If sender.Text.trim = String.Empty Then
            intSite = 0
        End If
    End Sub
    Private Sub txtItem_Leave(sender As Object, e As System.EventArgs) Handles txtItemCode.Leave, txtItemName.Leave
        If sender.Text.trim = String.Empty Then
            subPriClearItemDtls()
        End If
    End Sub
    Private Sub txtPromoter_Leave(sender As Object, e As System.EventArgs) Handles txtPromoterCode.Leave, txtPromoterName.Leave
        If sender.Text.trim = String.Empty Then
            intPromoter = 0
        End If
    End Sub
    Private Sub txtGoDown_leave(sender As Object, e As System.EventArgs) Handles txtGoDown.Leave
        If sender.Text.trim = String.Empty Then
            intGodownID = 0
        End If
    End Sub
End Class